import { detailPanelStyles } from './detailPanelStyles'
import { detailPanelScript } from './detailPanelScript'
import { generateTagsHtml } from './tagRenderer'
import { DetailPanelConfig } from './types'

export function generateDetailPanelHtml(config: DetailPanelConfig): string {
  const { record } = config

  // 转义文本内容
  const escapedProblem = escapeHtml(record.problem)
  const escapedSolution = escapeHtml(record.solution)
  const escapedCode = formatCodeSnippet(record.codeSnippet)
  const escapedFilePath = escapeHtml(record.filePath)

  return `
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>记录详情 #${record.id}</title>
        <style>${detailPanelStyles}</style>
    </head>
    <body>
        <div class="header">
            <div class="title">记录 #${record.id}</div>
            <div class="meta">
              创建时间: ${new Date(record.createdAt).toLocaleString('zh-CN')}
            </div>
            <div class="tags-section">
                <div class="tags-label">🏷️ 标签</div>
                ${generateTagsHtml(record.tags)}
            </div>
        </div>
        
        <div class="section">
            <div class="section-title">
              <span>📋</span>
              <span>问题描述</span>
            </div>
            <div class="content">${escapedProblem}</div>
        </div>
        
        <div class="section">
            <div class="section-title">
              <span>💡</span>
              <span>解决方案</span>
            </div>
            <div class="content">${escapedSolution}</div>
        </div>
        
        <div class="section">
            <div class="section-title">
              <span>📍</span>
              <span>文件位置</span>
            </div>
            <div class="file-info">
              ${escapedFilePath}:${record.lineRange}
            </div>
        </div>
        
        <div class="section">
            <div class="section-title">
              <span>📝</span>
              <span>相关代码</span>
            </div>
            <pre class="code-snippet"><code>${escapedCode || '(无选中代码)'}</code></pre>
        </div>

        <script>
            ${detailPanelScript}
            
            // 初始化页面
            document.addEventListener('DOMContentLoaded', function() {
              initializeDetailPanel(${record.id});
            });
        </script>
    </body>
    </html>
  `
}

function escapeHtml(text: string): string {
  if (!text) return ''
  return text.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;')
}

/**
 * 格式化代码片段，处理缩进和特殊字符
 */
function formatCodeSnippet(code: string): string {
  if (!code) return ''

  // 首先转义HTML字符
  let formatted = escapeHtml(code)

  // 标准化行分隔符
  formatted = formatted.replace(/\r\n/g, '\n').replace(/\r/g, '\n')

  // 移除开头和结尾的空行
  formatted = formatted.replace(/^\n+/, '').replace(/\n+$/, '')

  // 如果代码为空，返回提示
  if (!formatted.trim()) {
    return '(无选中代码)'
  }

  // 分析最小缩进，用于去除多余的公共缩进
  const lines = formatted.split('\n')
  const nonEmptyLines = lines.filter(line => line.trim().length > 0)

  if (nonEmptyLines.length === 0) {
    return '(无选中代码)'
  }

  // 找到最小缩进（排除空行）
  let minIndent = Infinity
  for (const line of nonEmptyLines) {
    const match = line.match(/^(\s*)/)
    if (match) {
      const indentLength = match[1].length
      if (indentLength < minIndent) {
        minIndent = indentLength
      }
    }
  }

  // 移除公共缩进，保持相对缩进关系
  if (minIndent > 0 && minIndent !== Infinity) {
    const normalizedLines = lines.map(line => {
      if (line.trim().length === 0) {
        return '' // 空行不处理
      }
      return line.substring(minIndent)
    })
    formatted = normalizedLines.join('\n')
  }

  return formatted
}
